package com.wangxi.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    /**
     * 将自定义的 Druid数据源添加到容器中，不再让 Spring Boot 自动创建
     * 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
     *
     * @ConfigurationProperties(prefix = "spring.datasource")：作用就是将 全局配置文件中
     * 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //配置druid数据源监控
    @Bean
    public ServletRegistrationBean registrationBean() {
        ServletRegistrationBean bean =
                new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("loginUsername", "root");
        paraMap.put("loginPassword", "123456");
        //后台页面允许谁访问
        //paraMap.put("allow", "")：为空或者为null时，表示允许所有访问
        //paraMap.put("allow", "localhost")：表示只有本机可以访问
        paraMap.put("allow", "");
        //后台页面拒绝谁访问
        //paraMap.put("zyy", "192.168.1.20");表示禁止此ip访问
        bean.setInitParameters(paraMap);
        return bean;
    }

    //配置druid web监控filter过滤器**
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        Map<String, String> paraMap = new HashMap<>();
        ////exclusions：设置哪些请求进行过滤排除掉，从而不进行统计
        paraMap.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(paraMap);
        //"/*" 表示过滤所有请求
//        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}
